<template>
  <div>
    <div>
      <we-button v-if="baseCode" @click="dialogFormVisible = true" type="primary" size="mini">
        <em class="el-icon-plus"></em> 新增
      </we-button>
      <we-button v-if="baseCode" @click="detailRow(currentRow)" type="primary" size="mini">
        <em class="el-icon-edit"></em> 修改
      </we-button>
      <we-button v-if="baseCode" @click="deleteRow"  type="primary" size="mini">
        <em class="el-icon-delete"></em> 删除
      </we-button>
      <span v-if="baseName">当前人员：【 {{baseName}} 】</span>
    </div>

    <!-- 表格 -->
    <el-table
      size="mini"
      height="116px"
      :header-cell-style="rowClass"
      :data="tableData"

      border
      highlight-current-row
      resizable
      ref="singleTable"
      @row-dblclick="detailRow"
      @current-change="handleCurrentChange"
      style="width: 100%; margin-top: 5px"
    >
      <el-table-column type="index" label="#"> </el-table-column>
      <el-table-column
        prop="degree_dictText"
        width="150"
        :show-overflow-tooltip="true"
        label="学历">
      </el-table-column>
      <el-table-column
        prop="subject_dictText"
        width="150"
        :show-overflow-tooltip="true"
        label="所学专业类型">
      </el-table-column>
      <el-table-column
        prop="subjectDesc"
        width="150"
        :show-overflow-tooltip="true"
        label="所学专业(描述)"
      >
      </el-table-column>
      <el-table-column
        prop="startDate"
        width="150"
        :show-overflow-tooltip="true"
        label="入学日期"
      >
      </el-table-column>
      <el-table-column
        prop="studyYear"
        width="150"
        :show-overflow-tooltip="true"
        label="学制"
      >
      </el-table-column>
      <el-table-column
        prop="degreeLevel_dictText"
        width="150"
        :show-overflow-tooltip="true"
        label="学位"
      >
      </el-table-column>
      <el-table-column
        prop="degreeType_dictText"
        width="150"
        :show-overflow-tooltip="true"
        label="学位性质"
      >
      </el-table-column>
      <el-table-column
        prop="doubleDegreeDesc"
        width="150"
        :show-overflow-tooltip="true"
        label="双学位描述"
      >
      </el-table-column>
      <el-table-column
        prop="graduateDate"
        width="150"
        :show-overflow-tooltip="true"
        label="毕业日期"
      >
      </el-table-column>
      <el-table-column
        prop="graduateSchool"
        width="150"
        :show-overflow-tooltip="true"
        label="毕业学校"
      >
      </el-table-column>
      <el-table-column
        prop="educationType_dictText"
        width="150"
        :show-overflow-tooltip="true"
        label="教育类别"
      >
      </el-table-column>
      <el-table-column
        prop="studyType_dictText"
        width="150"
        :show-overflow-tooltip="true"
        label="学习形式"
      >
      </el-table-column>
      <el-table-column
        prop="degreeNo"
        width="150"
        :show-overflow-tooltip="true"
        label="学历证书号"
      >
      </el-table-column>
      <el-table-column
        prop="degreeLevelNo"
        width="150"
        :show-overflow-tooltip="true"
        label="学位证书号"
      >
      </el-table-column>
      <el-table-column
        prop="degreeGetDate"
        width="150"
        :show-overflow-tooltip="true"
        label="学位授予日期"
      >
      </el-table-column>
      <el-table-column
        prop="degreeGetDepart"
        width="150"
        :show-overflow-tooltip="true"
        label="学位授予单位"
      >
      </el-table-column>
      <el-table-column
        prop="degreeGetCountry_dictText"
        width="150"
        :show-overflow-tooltip="true"
        label="学位授予国家(地区)"
      >
      </el-table-column>
      <!-- <el-table-column fixed="right" label="操作" width="180">
        <template slot-scope="scope">
          <we-button @click="detailRow(scope.row)" type="primary" size="mini"
            >详情</we-button
          >
          <we-button
            @click="deleteRow(scope.row)"
            type="danger"
            size="mini"
            >删除</we-button
          >
        </template>
      </el-table-column> -->
    </el-table>
    <div class="table_tools">
      <we-pagination
        :total="pagination.total"
        :page="pagination.pageNum"
        :pageSize="pagination.pageSize"
        @currentChange="currentChange($event)"></we-pagination>
    </div>
    <!-- 表格 -->

    <!-- 新增弹窗 -->
    <el-dialog
      title="学历学位子集"
      :visible.sync="dialogFormVisible"
      @close="handleOffDialog"
      append-to-body
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="140px"
        size="mini"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学历" prop="degree">
              <el-cascader
                class="inputW"
                v-model="ruleForm.degree"
                :options="allDegree"
                :props="{ expandTrigger: 'hover' ,value:'uuid',label:'name',children: 'children'}"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所学专业类别" prop="subject">
              <el-cascader
                class="inputW"
                v-model="ruleForm.subject"
                :options="allMajor"
                :props="{ expandTrigger: 'hover' ,value:'uuid',label:'name',children: 'children'}"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所学专业(描述)" prop="subjectDesc">
              <el-input
                class="inputW"
                v-model="ruleForm.subjectDesc"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入学日期" prop="startDate">
              <el-date-picker
                class="inputW"
                v-model="ruleForm.startDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学制" prop="studyYear">
              <el-input
                class="inputW"
                v-model.number="ruleForm.studyYear"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学位" prop="degreeLevel">
              <el-cascader
                class="inputW"
                v-model="ruleForm.degreeLevel"
                :options="degreeLevel"
                :props="{ expandTrigger: 'hover' ,value:'uuid',label:'name',children: 'children'}"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学位性质" prop="degreeType">
              <el-select
                class="inputW"
                v-model="ruleForm.degreeType"
                placeholder="请选择"
                clearable
              >
              <el-option v-for="item in natureLearning" :key="item.uuid" :label="item.name" :value="item.uuid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="双学位描述" prop="doubleDegreeDesc">
              <el-input
                class="inputW"
                v-model="ruleForm.doubleDegreeDesc"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="毕业日期" prop="graduateDate">
              <el-date-picker
                class="inputW"
                v-model="ruleForm.graduateDate"
                type="date"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
                placeholder="选择日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="毕业学校" prop="graduateSchool">
              <el-input
                class="inputW"
                v-model="ruleForm.graduateSchool"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="教育类别" prop="educationType">
              <el-select
                class="inputW"
                v-model="ruleForm.educationType"
                placeholder="请选择"
                clearable
              >
                <el-option v-for="item in educationCategory" :key="item.uuid" :label="item.name" :value="item.uuid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学习形式" prop="studyType">
              <el-select
                class="inputW"
                v-model="ruleForm.studyType"
                placeholder="请选择"
                clearable
              >
                <el-option v-for="item in learningform" :key="item.uuid" :label="item.name" :value="item.uuid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学历证书号" prop="degreeNo">
              <el-input
                class="inputW"
                v-model="ruleForm.degreeNo"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学位证书号" prop="degreeLevelNo">
              <el-input
                class="inputW"
                v-model="ruleForm.degreeLevelNo"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学位授予日期" prop="degreeGetDate">
              <el-date-picker
                class="inputW"
                v-model="ruleForm.degreeGetDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学位授予单位" prop="degreeGetDepart">
              <el-input
                class="inputW"
                v-model="ruleForm.degreeGetDepart"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学位授予国家(地区)" prop="degreeGetCountry">
              <el-select
                class="inputW"
                v-model="ruleForm.degreeGetCountry"
                placeholder="请选择"
                clearable
                filterable
              >
                <el-option v-for="item in allCountry" :key="item.uuid" :label="item.name" :value="item.uuid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12"> </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <we-button size="mini" @click="dialogFormVisible = false"
          >取 消</we-button
        >
        <we-button v-if="!isUpdate" size="mini" type="primary" @click="submitForm('ruleForm')"
          >新 增</we-button
        >
        <we-button v-if="isUpdate" size="mini" type="primary" @click="updateForm('ruleForm')"
          >修 改</we-button
        >
      </div>
    </el-dialog>
    <!-- 新增弹窗 -->
  </div>
</template>

<script>
import WeButton from '@/components/WeButton'
import WePagination from '@/components/WePagination'
import { parseTree } from '@/utils/util'
import { getAction, postAction, deleteAction } from '@/api/manage'
import {bus} from "@/utils/eventBus";
import {opDictNew, staffDegree} from "@/api/apiUrl";
export default {
  components: {
    WeButton,
    WePagination
  },
  data () {
    const checkStudyYear = (rule, value, callback) => {
      if (value) {
        if (!Number.isInteger(value)) {
          callback(new Error('请输入数字值'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      isUpdate: false,
      pagination: {
        total: 10, // 总数据条数
        pageSize: 10, // 每页条数
        pageNum: 1 // 当前页
      }, // 列表分页数据
      tableData: [],
      currentRow: null,
      dialogFormVisible: false,
      ruleForm: {
        degree: '',
        subject: '',
        subjectDesc: '',
        startDate: '',
        studyYear: '',
        degreeLevel: '',
        degreeType: '',
        doubleDegreeDesc: '',
        graduateDate: '',
        graduateSchool: '',
        educationType: '',
        studyType: '',
        degreeNo: '',
        degreeLevelNo: '',
        degreeGetDate: '',
        degreeGetDepart: '',
        degreeGetCountry: '',
        uuidList:[],
      },
      rules: {
        degree: [{ required: true, message: '请选择学历', trigger: 'change' }],
        subject: [
          { required: true, message: '请选择所学专业类型', trigger: 'change' }
        ],
        subjectDesc: [
          { required: true, message: '请填写所学专业(描述)', trigger: 'blur' }
        ],
        studyYear: [{ validator: checkStudyYear, trigger: 'blur' }],
        graduateDate: [
          { required: true, message: '请选择毕业日期', trigger: 'change' }
        ],
        graduateSchool: [
          { required: true, message: '请填写毕业学校', trigger: 'blur' }
        ],
        educationType: [
          { required: true, message: '请选择教育类别', trigger: 'change' }
        ]
      },
      allDegree: [], // 学历
      allMajor: [], // 专业
      allCountry: [], // 国家
      natureLearning: [], // 学习性质字典
      educationCategory: [], // 教育类别字典
      learningform: [], // 学习形式
      degreeLevel: [], // 学位
      baseCode: '',
      baseName: '',
      baseCodes: []
    }
  },
  watch: {
    dialogFormVisible () {
      if (this.dialogFormVisible === false) {
        if (this.isUpdate) {
          setTimeout(() => {
            this.isUpdate = false
            this.clearForm()
            if (this.$refs.ruleForm !== undefined) {
              this.$refs.ruleForm.resetFields()
            }
          }, 500)
        }
        if (this.$store.state.degree === true) {
          this.$store.commit('changeDegree', false)
        }
      }
    },
    '$store.state.baseCode'(newval) {
      this.baseCode  = newval
      this.selectByBaseCode()
    },
    '$store.state.baseName'(newval) {
      this.baseName  = newval
    },
    '$store.state.degree' (newval) {
      if (newval === true) {
        this.dialogFormVisible = true
        if (this.$store.state.updateSubset === true) {
          this.isUpdate = true
        } else {
          this.isUpdate = false
        }
        this.$store.commit('changeUpdateSubset', false)
        this.baseCodes = this.$store.state.baseCodes
        this.getAllDegree()
        this.getAllMajor()
        this.getAllCountry()
        this.getNatureLearning()
        this.getEducationCategory()
        this.getLearningForm()
        this.getDegreeLevel()
      }
    }
  },
  methods: {
    clickSubset () {
      this.baseCode = this.$store.state.baseCode
      this.baseCodes = []
      this.getAllDegree()
      this.getAllMajor()
      this.getAllCountry()
      this.getNatureLearning()
      this.getEducationCategory()
      this.getLearningForm()
      this.selectByBaseCode()
      this.getDegreeLevel()
    },
    batchAdd(data){
      this.dialogFormVisible = true
      this.ruleForm.uuidList = data
    },
    /**
     * 新增学历信息
     */
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const data = JSON.parse(JSON.stringify(this.ruleForm))
          data.subject = data.subject.pop()
          data.degree = data.degree.pop()
          if (data.degreeLevel) {
            data.degreeLevel = data.degreeLevel.pop()
          }
          data.baseCode = this.baseCode
          data.sysOrgCode = '测试部门'
          data.createUser = '测试员'
          if (this.$store.state.degree === true) {
            for (let i = 0; i < this.baseCodes.length; i++) {
              data.baseCode = this.baseCodes[i]
              postAction(staffDegree.add, data)
                .then(result => {
                  if (result.code === 200) {
                    this.dialogFormVisible = false
                    bus.$emit('handleDialog')
                    this.$message({
                      type: 'success',
                      message: '新增成功!'
                    })
                    this.clearForm()
                  } else {
                    this.$message({
                      type: 'waring',
                      message: result.msg
                    })
                  }
                })
            }
          } else {
            postAction(staffDegree.add, data)
              .then(result => {
                if (result.code === 200) {
                  this.dialogFormVisible = false
                  bus.$emit('handleDialog')
                  this.selectByBaseCode()
                  this.$message({
                    type: 'success',
                    message: '新增成功!'
                  })
                } else {
                  this.$message({
                    type: 'waring',
                    message: result.msg
                  })
                }
              })
          }
        } else {
          return false
        }
      })
    },

    handleCurrentChange(val) {
        this.currentRow = val;
    },

    /**
     * 删除
     */
    deleteRow (row) {
      if(!this.currentRow){
        this.$message("请选择要删除的数据！")
        return
      }
      this.$confirm('是否要删除这条数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteAction(staffDegree.delete, { uuids: [this.currentRow.uuid] })
            .then((res) => {
              if (res.code === 200) {
                this.selectByBaseCode()
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
              } else {
                this.$message({
                  type: 'waring',
                  message: res.msg
                })
              }
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    /**
     * 修改
     */
    updateForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const data = JSON.parse(JSON.stringify(this.ruleForm))
          if (typeof (this.ruleForm.subject) !== 'string') {
            data.subject = this.ruleForm.subject.pop()
          }
          if (typeof (this.ruleForm.degree) !== 'string') {
            data.degree = this.ruleForm.degree.pop()
          }
          if (typeof (this.ruleForm.degreeLevel) !== 'string') {
            data.degreeLevel = this.ruleForm.degreeLevel.pop()
          }
          data.updateUser = '修改员'
          postAction(staffDegree.update, data)
            .then(result => {
              if (result.code === 200) {
                this.dialogFormVisible = false
                bus.$emit('handleDialog')
                this.selectByBaseCode()
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                })
              } else {
                this.$message({
                  type: 'waring',
                  message: result.msg
                })
              }
            })
        } else {
          return false
        }
      })
    },
    handleOffDialog() {
      this.dialogFormVisible = false
      bus.$emit('handleDialog')
    },
    /**
     * 查询
     */
    selectByBaseCode () {
      let self = this
      postAction(staffDegree.pageList, { baseCode: this.baseCode,size:this.pagination.pageSize,page:this.pagination.pageNum })
        .then(result => {
          if (result.code === 200) {
            if (!result.data.list.length && self.pagination.pageNum !== 1) {
              self.pagination.pageNum -= 1
              self.selectByBaseCode()
              return
            }
            if (self.pagination.pageNum === 1 && result.data.list.length === 0) {
              self.pagination.total = 0
            } else {
              self.pagination.total = result.data.total
            }
            self.tableData = result.data.list
          }
        })
    },

    /**
     * 查询学历表
     */
    getAllDegree () {
      getAction(`${opDictNew.findTreeByType}?type=education` )
        .then((res) => {
          if (res.code === 200) {
            this.allDegree = res.data
          }
        })
    },

    /**
     * 查询学位表
     */
    getDegreeLevel () {
      getAction(`${opDictNew.findTreeByType}?type=rs_an` )
        .then((res) => {
          if (res.code === 200) {
            this.degreeLevel = res.data
          }
        })
    },

    /**
     * 查询专业表
     */
    getAllMajor () {
      getAction(`${opDictNew.findTreeByType}?type=rs_ai`)
        .then((res) => {
          if (res.code === 200) {
            this.allMajor = res.data
          }
        })
    },

    /**
     * 查询国家
     */
    getAllCountry () {
      getAction(`${opDictNew.findTreeByType}?type=rs_ad`)
        .then((res) => {
          if (res.code === 200) {
            this.allCountry = res.data
          }
        })
    },

    /**
     * 获取学习性质字典
     */
    async getNatureLearning () {
      const result = await getAction(opDictNew.findByType, {
        type: 'rs_xwxz'
      })
      this.natureLearning = result.data
    },

    /**
     * 获取教育类别字典
     */
    async getEducationCategory () {
       const result = await getAction(opDictNew.findByType, {
        type: 'rs_jylb'
      })
      this.educationCategory = result.data
    },

    /**
     * 获取学习形式字典
     */
    async getLearningForm () {
       const result = await getAction(opDictNew.findByType, {
        type: 'rs_bs'
      })
      this.learningform = result.data
    },

    /**
     * 详情
     */
    detailRow (row) {
      if(!row){
        this.$message("请选择要编辑的数据！")
        return
      }
      this.ruleForm = JSON.parse(JSON.stringify(row))
      this.isUpdate = true
      this.dialogFormVisible = true
    },

    // 当前页改变
    currentChange (event) {
      this.pagination.pageNum = event
      this.selectByBaseCode()
    },

    /**
     * 清除form
     */
    clearForm () {
      this.ruleForm = {
        degree: '',
        subject: '',
        subjectDesc: '',
        startDate: '',
        studyYear: '',
        degreeLevel: '',
        degreeType: '',
        doubleDegreeDesc: '',
        graduateDate: '',
        graduateSchool: '',
        educationType: '',
        studyType: '',
        degreeNo: '',
        degreeLevelNo: '',
        degreeGetDate: '',
        degreeGetDepart: '',
        degreeGetCountry: ''
      }
    },

    handleClose () {},
    handleChange () {},
    rowClass ({ row, rowIndex }) {
      return 'background:rgba(248, 248, 249, 1);color:#000;'
    }
  }
}
</script>

<style scoped>


.table_tools {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
